package com.fwzc.giuseppe.activity;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.fwzc.giuseppe.R;
import com.fwzc.giuseppe.Api.Api;
import com.fwzc.giuseppe.adapter.UniversalAdapter;
import com.fwzc.giuseppe.base.BaseActivity;
import com.fwzc.giuseppe.dao.UserKeyDao;
import com.fwzc.giuseppe.entity.ClassEntity;
import com.fwzc.giuseppe.entity.School;
import com.fwzc.giuseppe.entity.UserKey;
import com.fwzc.giuseppe.util.BitmapUtils;
import com.fwzc.giuseppe.util.DialogUtils;
import com.fwzc.giuseppe.util.ViewHolder;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.bitmap.BitmapDisplayConfig;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class HomepageActivity extends BaseActivity implements OnClickListener {
	public DrawerLayout drawerLayout;
	private LinearLayout left_menu_layout;
	RelativeLayout favorites, not_receiving, had_receiving, all_orders,
			invitation, setting, message;
	/** 再按一次退出程序 */
	private long exitTime = 0;
	private ImageView person_center;
	private TextView title, switchover;
	private ImageView user_head ,user_head_inside;
	private RelativeLayout info_sex, info_height, info_weight, info_birthday,
			info_school, info_class;
	private TextView sex, height, weight, birthday, school, classes, exit,
			alert, height_alert, name, nameInside, schoolInside, male, female;
	private RelativeLayout uniform, schedule, watch, sleep;

	private ProgressDialog load;
	private HttpUtils httpUtil;
	private ImageLoader imageLoader;
	private DisplayImageOptions option;
	private BitmapDisplayConfig config;
	private String userId, userIdentityNumber;
	private String heightMSG, alertMsg, classMSG, news;
	private Dialog alertDialog, heightDialog, dateDialog, sexDialog,
			schoolDialog, classDialog;
	private RelativeLayout alert_view, height_view, dateView, sexView,
			schoolView, classView;
	private Button certain, ignore, update, cancel, sure;
	private DatePicker datepicker;
	private String flage = "complete", birthdayStr = "", sexStr="";
	private ListView ListView_school, ListView_class;
	private List<School> schoolList = new ArrayList<School>();
	private UniversalAdapter<School> schoolAdapter;
	private UniversalAdapter<ClassEntity> classAdapter;
	private List<ClassEntity> classlList = new ArrayList<ClassEntity>();

	private String schoolId = "", gardeId = "", classId = "", gender = "",
			weightStr = "", heightStr = "", nameStr = "";
	private final int heightCode = 1, weightCode = 2, nameCode = 3;
	private boolean date_null;
	//头像选择
	private Dialog dialog;
	private RelativeLayout choice_photo;
	private Button camera, album, cancel_phone;
	private final static int CAMERACode = 101, ALBUM = 100, CROP = 102;
	private final static String TEMP = "phone.jpg";
	private File tempFile;
	private UserKeyDao dao;
	private boolean first = true;
	private  File f;
	private Bitmap bitmap;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.homepage);

		initLeftLayout();
		initView();
		initList();
		initClick();
		iniData();
	}

	@SuppressLint("InflateParams") 
	public void initLeftLayout() {
		drawerLayout = (DrawerLayout) findViewById(R.id.main_homepage);
		// 左边菜单
		left_menu_layout = (LinearLayout) findViewById(R.id.main_left_drawer_layout);

		View view = getLayoutInflater().inflate(R.layout.person_center, null);
		nameInside = (TextView) view.findViewById(R.id.name);
		schoolInside = (TextView) view.findViewById(R.id.school);
		user_head_inside = (ImageView) view.findViewById(R.id.userheadinside);
		left_menu_layout.addView(view);
	}

	@SuppressLint("InflateParams")
	private void initView() {
		dao = new UserKeyDao(this);
		// 网络请求相关
		httpUtil = new HttpUtils();
		imageLoader = ImageLoader.getInstance();
		option = new DisplayImageOptions.Builder().cacheInMemory(true).imageScaleType(ImageScaleType.EXACTLY).cacheOnDisk(true).bitmapConfig(Bitmap.Config.RGB_565).displayer(new RoundedBitmapDisplayer(120)).build();
		imageLoader.init(ImageLoaderConfiguration.createDefault(this));
		config = new BitmapDisplayConfig();
		config.setLoadFailedDrawable(getResources().getDrawable(R.drawable.user_img_bg));
		load = new ProgressDialog(this);
		load.setMessage(getResources().getString(R.string.deal));
		load.setCancelable(false);

		uniform = (RelativeLayout) findViewById(R.id.uniform);
		uniform.setOnClickListener(this);
		schedule = (RelativeLayout) findViewById(R.id.schedule);
		schedule.setOnClickListener(this);
		watch = (RelativeLayout) findViewById(R.id.watch);
		watch.setOnClickListener(this);
		sleep = (RelativeLayout) findViewById(R.id.sleep);
		sleep.setOnClickListener(this);
		title = (TextView) findViewById(R.id.title);
		switchover = (TextView) findViewById(R.id.switchover);
		title.setText("个人信息");
		switchover.setText("切换账号");
		switchover.setOnClickListener(this);
		person_center = (ImageView) findViewById(R.id.person_center);
		person_center.setOnClickListener(this);
		exit = (TextView) findViewById(R.id.exit);
		exit.setOnClickListener(this);
		favorites = (RelativeLayout) findViewById(R.id.favorites);
		favorites.setOnClickListener(this);
		not_receiving = (RelativeLayout) findViewById(R.id.not_receiving);
		not_receiving.setOnClickListener(this);
		had_receiving = (RelativeLayout) findViewById(R.id.had_receiving);
		had_receiving.setOnClickListener(this);
		all_orders = (RelativeLayout) findViewById(R.id.all_orders);
		all_orders.setOnClickListener(this);
		invitation = (RelativeLayout) findViewById(R.id.invitation);
		invitation.setOnClickListener(this);
		setting = (RelativeLayout) findViewById(R.id.setting);
		setting.setOnClickListener(this);
		message = (RelativeLayout) findViewById(R.id.message);
		message.setOnClickListener(this);

		user_head = (ImageView) findViewById(R.id.userhead);
		info_sex = (RelativeLayout) findViewById(R.id.info_sex);
		info_height = (RelativeLayout) findViewById(R.id.info_height);
		info_weight = (RelativeLayout) findViewById(R.id.info_weight);
		info_birthday = (RelativeLayout) findViewById(R.id.info_birthday);
		info_school = (RelativeLayout) findViewById(R.id.info_school);
		info_class = (RelativeLayout) findViewById(R.id.info_class);

		sex = (TextView) findViewById(R.id.tv_sex);
		height = (TextView) findViewById(R.id.tv_height);
		weight = (TextView) findViewById(R.id.tv_weight);
		birthday = (TextView) findViewById(R.id.tv_birthday);
		school = (TextView) findViewById(R.id.tv_school);
		classes = (TextView) findViewById(R.id.tv_classes);
		name = (TextView) findViewById(R.id.name);

		info_sex.setOnClickListener(this);
		info_height.setOnClickListener(this);
		info_weight.setOnClickListener(this);
		info_birthday.setOnClickListener(this);
		info_school.setOnClickListener(this);
		info_class.setOnClickListener(this);

		alert_view = (RelativeLayout) LayoutInflater.from(this).inflate(
				R.layout.dialog_delete, null);
		height_view = (RelativeLayout) LayoutInflater.from(this).inflate(
				R.layout.height_alert, null);
		dateView = (RelativeLayout) LayoutInflater.from(this).inflate(
				R.layout.date_dialog, null);
		sexView = (RelativeLayout) LayoutInflater.from(this).inflate(
				R.layout.sex_dialog_view, null);
		schoolView = (RelativeLayout) LayoutInflater.from(this).inflate(
				R.layout.school_dialog, null);
		classView = (RelativeLayout) LayoutInflater.from(this).inflate(
				R.layout.class_dialog, null);
		ignore = (Button) height_view.findViewById(R.id.ignore);
		update = (Button) height_view.findViewById(R.id.update);
		cancel = (Button) dateView.findViewById(R.id.cancel);
		datepicker = (DatePicker) dateView.findViewById(R.id.datepicker);
		male = (TextView) sexView.findViewById(R.id.male);
		female = (TextView) sexView.findViewById(R.id.female);
		sure = (Button) dateView.findViewById(R.id.certain);
		height_alert = (TextView) height_view.findViewById(R.id.content_tv);
		certain = (Button) alert_view.findViewById(R.id.delete);
		alert = (TextView) alert_view.findViewById(R.id.content_tv);
		ListView_school = (ListView) schoolView.findViewById(R.id.datelist);
		ListView_class = (ListView) classView.findViewById(R.id.datelist);
		alertDialog = new Dialog(this);
		heightDialog = new Dialog(this);
		dateDialog = new Dialog(this);
		sexDialog = new Dialog(this);
		schoolDialog = new Dialog(this);
		classDialog = new Dialog(this);
		alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		heightDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dateDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		sexDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		schoolDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		classDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		alertDialog.setContentView(alert_view);
		heightDialog.setContentView(height_view);
		dateDialog.setContentView(dateView);
		sexDialog.setContentView(sexView);
		schoolDialog.setContentView(schoolView);
		classDialog.setContentView(classView);
		alertDialog.setCancelable(false);
		heightDialog.setCancelable(false);
		
		choice_photo = (RelativeLayout) LayoutInflater.from(this).inflate(
				R.layout.choice, null);
		camera = (Button) choice_photo.findViewById(R.id.camera);
		album = (Button) choice_photo.findViewById(R.id.album);
		cancel_phone = (Button) choice_photo.findViewById(R.id.cancel);
		dialog = new Dialog(this);
		dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		dialog.setContentView(choice_photo);
	}

	private void initList() {
		schoolAdapter = new UniversalAdapter<School>(this, schoolList,
				R.layout.text_item) {

			@Override
			public void convert(ViewHolder viewHolder, School school) {
				TextView content = (TextView) viewHolder.getView(R.id.content);
				content.setText(school.name);
			}
		};

		classAdapter = new UniversalAdapter<ClassEntity>(this, classlList,
				R.layout.text_item) {

			@Override
			public void convert(ViewHolder viewHolder, ClassEntity item) {
				TextView content = (TextView) viewHolder.getView(R.id.content);
				content.setText(item.name);
			}
		};
		ListView_school.setAdapter(schoolAdapter);
		ListView_class.setAdapter(classAdapter);
	}

	private void iniData(){
		userId = getSharedPreferences("user", Activity.MODE_PRIVATE).getString(
				"userId", "");
		userIdentityNumber = getSharedPreferences("user", Activity.MODE_PRIVATE)
				.getString("userIdentityNumber", "");
		getUserInfo();
	}


	private void initClick() {
		certain.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();

				if ("alertMsg".equals(flage)&&alertMsg!=null&&alertMsg!="null") {
					alert.setText(alertMsg);
					alertDialog.show();
					flage = "classMSG";
					return;
				}

				if ("classMSG".equals(flage)&&classMSG!=null&&classMSG!="null") {
					alert.setText(classMSG);
					alertDialog.show();
					flage = "heightMSG";
					return;
				}

				if ("heightMSG".equals(flage)&&heightMSG!=null&&heightMSG!="null") {
					height_alert.setText("您已经" + heightMSG + "个月没有更新身高体重信息了");
					heightDialog.show();
					flage = "nomal";
					return;
				}
			}
		});

		ignore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				heightDialog.dismiss();
			}
		});

		update.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				heightDialog.dismiss();
				Intent heightIntent = new Intent(HomepageActivity.this,
						UpdateInfoActivity.class);
				heightIntent.putExtra("flage", 1);
				heightIntent.putExtra("userId", userId);
				heightIntent.putExtra("userIdentityNumber", userIdentityNumber);
				startActivityForResult(heightIntent, heightCode);
			}
		});

		cancel.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dateDialog.dismiss();
			}
		});

		sure.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dateDialog.dismiss();
				birthdayStr = String.format("%d-%02d-%02d",datepicker.getYear(), datepicker.getMonth() + 1,datepicker.getDayOfMonth());
				updateInfo(3,-1);
			}
		});

		male.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sexDialog.dismiss();
				sexStr = "男";
				gender = "1";
				updateInfo(2,-1);
			}
		});

		female.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				sexDialog.dismiss();
				sexStr = "女";
				gender = "2";
				updateInfo(2,-1);
			}
		});

		ListView_school.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				schoolDialog.dismiss();
				schoolId = schoolList.get(position).id;
				updateInfo(4,position);
			}
		});

		ListView_class.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				classDialog.dismiss();
				gardeId = classlList.get(position).gradeId;
				classId = classlList.get(position).id;
				updateInfo(5,position);
			}
		});

		name.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(HomepageActivity.this,
						UpdateInfoActivity.class);
				intent.putExtra("flage", 3);
				intent.putExtra("userId", userId);
				intent.putExtra("userIdentityNumber", userIdentityNumber);
				startActivityForResult(intent, nameCode);
			}
		});
		
		user_head.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Window window = dialog.getWindow();
				window.setGravity(Gravity.BOTTOM);
				window.setWindowAnimations(R.style.mydialog);
				dialog.show();
				window.getDecorView().setPadding(0, 0, 0, 0);
				WindowManager.LayoutParams params = window.getAttributes();
				params.width = WindowManager.LayoutParams.MATCH_PARENT;
				params.height = WindowManager.LayoutParams.WRAP_CONTENT;
				window.setAttributes(params);
			}
		});
		
		cancel_phone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog.dismiss();
			}
		});

		camera.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!Environment.getExternalStorageState().equals(
						android.os.Environment.MEDIA_MOUNTED)) {
					showToast("请插入存储卡再试");
					return;
				} else {
					if (tempFile == null) {
						tempFile = new File(Environment
								.getExternalStorageDirectory(), TEMP);
					}
				}
				Intent cameraIntent = new Intent(
						MediaStore.ACTION_IMAGE_CAPTURE);
				cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(tempFile));
				startActivityForResult(cameraIntent, CAMERACode);
			}
		});

		album.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				startActivityForResult(intent, ALBUM);
			}
		});
	}

	// 提交更改
	private void updateInfo(final int flage,final int position) {
		RequestParams params = new RequestParams("UTF-8");
		params.addBodyParameter("type", "1");
		params.addBodyParameter("userId", userId);
		params.addBodyParameter("userIdentityNumber", userIdentityNumber);
		params.addBodyParameter("gender", gender);
		params.addBodyParameter("weight", weightStr);
		params.addBodyParameter("height", heightStr);
		params.addBodyParameter("birthday", birthdayStr);
		params.addBodyParameter("schoolId", schoolId);
		params.addBodyParameter("classId", classId);
		params.addBodyParameter("name", nameStr);
		params.addBodyParameter("gardeId", gardeId);
		if(f!=null){
			params.addBodyParameter(f.getPath(), f);
		}
		// 发送json类型的数据
		httpUtil.send(HttpRequest.HttpMethod.POST, Api.GET_USERINFO, params,
				new RequestCallBack<String>() {

					@Override
					public void onStart() {
						load.show();
					}

					@Override
					public void onFailure(HttpException arg0, String response) {
						load.dismiss();
						showToast("加载数据失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseStr) {
						try {
							JSONObject response = new JSONObject(
									responseStr.result);
							int resultCode = response.getInt("resultCode");
							if (resultCode == 5) {
								load.dismiss();
								switch (flage) {
								case 1:
									user_head.setImageBitmap(BitmapUtils.toRoundBitmap(bitmap, 120));
									user_head_inside.setImageBitmap(BitmapUtils.toRoundBitmap(bitmap, 120));
									f.delete();
									break;
								case 2:
									sex.setText(sexStr);
									break;
									
								case 3:
									birthday.setText(birthdayStr);
									break;
								case 4:
									school.setText(schoolList.get(position).name);
									schoolInside.setText(schoolList.get(position).name);
									break;
								case 5:
									classes.setText(classlList.get(position).name);
									break;
								default:
									break;
								}
							} else {
								load.dismiss();
								showToast(response.getString("msg"));
								f.delete();
							}
						} catch (JSONException e) {
							load.dismiss();
							showToast("解析出错");
						}

					}
				});
	}

	private void getUserInfo() {
		RequestParams params = new RequestParams("UTF-8");
		params.addBodyParameter("userId", userId);
		params.addBodyParameter("userIdentityNumber", userIdentityNumber);
		params.addBodyParameter("type", "0");
		// 发送json类型的数据
		httpUtil.send(HttpRequest.HttpMethod.POST, Api.GET_USERINFO, params,
				new RequestCallBack<String>() {

					@Override
					public void onStart() {
						load.show();
					}

					@Override
					public void onFailure(HttpException arg0, String response) {
						load.dismiss();
						showToast("加载数据失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseStr) {
						try {
							JSONObject response = new JSONObject(
									responseStr.result);
							int resultCode = response.getInt("resultCode");
							// resultCode=2用户信息不存在
							if (resultCode == 0) {
								JSONObject info = response
										.getJSONObject("dataList");
								switch (info.getInt("gender")) {
								case 1:
									sex.setText("男");
									break;
								case 2:
									sex.setText("女");
									break;
								default:
									sex.setText("保密");
									break;
								}
								String imageurl = info.getString("imageurl");
								height.setText(info.getString("height") + "cm");
								weight.setText(info.getString("weight") + "kg");
								birthday.setText(info.getString("birthyear")
										+ "-" + info.getString("birthmonth")
										+ "-" + info.getString("birthday"));
								school.setText(info.getString("schoolname"));
								name.setText(info.getString("name"));
								nameInside.setText(info.getString("name"));
								schoolInside.setText(info
										.getString("schoolname"));
								classes.setText(info.getString("className"));
								imageLoader.displayImage(imageurl, user_head, option);
								imageLoader.displayImage(imageurl, user_head_inside, option);
								UserKey userKey = new UserKey();
								userKey.name = info.getString("name");
								userKey.headPortrait = imageurl;
								dao.updateInfo(userId, userKey);
								load.dismiss();
								if(first == true){
									sendRequest();
									first = false;
									}
							} else if (resultCode == 2) {
								load.dismiss();
								alert.setText("第一次使用请完善个人资料");
								alertDialog.show();
								flage = "info";
								date_null = true;
								if(first == true){
								sendRequest();
								first = false;
								}
							}
							else {
								load.dismiss();
								showToast(response.getString("msg"));
							}
						} catch (JSONException e) {
							load.dismiss();
							showToast("解析出错");
						}

					}
				});
	}

	private void sendRequest() {
		RequestParams params = new RequestParams("UTF-8");
		params.addBodyParameter("userId", userId);
		// 发送json类型的数据
		httpUtil.send(HttpRequest.HttpMethod.POST, Api.SHOW_NEWS, params,
				new RequestCallBack<String>() {

					@Override
					public void onStart() {
						load.show();
					}

					@Override
					public void onFailure(HttpException arg0, String response) {
						load.dismiss();
						showToast("加载数据失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseStr) {
						try {
							JSONObject response = new JSONObject(
									responseStr.result);
							int resultCode = response.getInt("resultCode");
							if (resultCode == 0) {
								heightMSG = response.getString("heightMSG");
								alertMsg = response.getString("alert");
								classMSG = response.getString("classMSG");
								JSONArray ja = response
										.getJSONArray("dataList");
								news = ja.toString();
								load.dismiss();
								if (alertMsg!=null&&alertMsg!="null") {
									alert.setText(alertMsg);
									alertDialog.show();
									flage = "classMSG";
								}
							} else{
								load.dismiss();
							}
						} catch (JSONException e) {
							load.dismiss();
							showToast("解析出错");
						}

					}
				});
	}

	private void getAllSchool() {
		RequestParams params = new RequestParams("UTF-8");
		// 发送json类型的数据
		httpUtil.send(HttpRequest.HttpMethod.POST, Api.ALLSCHOOL, params,
				new RequestCallBack<String>() {

					@Override
					public void onStart() {
						load.show();
					}

					@Override
					public void onFailure(HttpException arg0, String response) {
						load.dismiss();
						showToast("加载数据失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseStr) {
						try {
							JSONObject response = new JSONObject(
									responseStr.result);
							int resultCode = response.getInt("resultCode");
							if (resultCode == 1) {
								JSONArray ja = response
										.getJSONArray("dataList");
								for (int i = 0; i < ja.length(); i++) {
									School school = new School();
									school.id = ja.getJSONObject(i).getString(
											"schoolid");
									school.name = ja.getJSONObject(i)
											.getString("schoolname");
									schoolList.add(school);
								}
								schoolAdapter.notifyDataSetChanged();
								load.dismiss();
								schoolDialog.show();
							} else {
								load.dismiss();
								showToast(response.getString("msg"));
							}
						} catch (JSONException e) {
							load.dismiss();
							showToast("解析出错");
						}

					}
				});
	}

	private void getClassBySchool() {
		RequestParams params = new RequestParams("UTF-8");
		params.addBodyParameter("schoolId", schoolId);
		// 发送json类型的数据
		httpUtil.send(HttpRequest.HttpMethod.POST, Api.GETCLASS, params,
				new RequestCallBack<String>() {

					@Override
					public void onStart() {
						load.show();
					}

					@Override
					public void onFailure(HttpException arg0, String response) {
						load.dismiss();
						showToast("加载数据失败");
					}

					@Override
					public void onSuccess(ResponseInfo<String> responseStr) {
						try {
							JSONObject response = new JSONObject(
									responseStr.result);
							int resultCode = response.getInt("resultCode");
							if (resultCode == 0) {
								JSONArray ja = response
										.getJSONArray("datalist");
								for (int i = 0; i < ja.length(); i++) {
									JSONObject grade = ja.getJSONObject(i);
									String gradeId = grade.getString("gradeId");
									JSONArray classArray = grade
											.getJSONArray("classlist");
									for (int j = 0; j < classArray.length(); j++) {
										ClassEntity entity = new ClassEntity();
										entity.gradeId = gradeId;
										entity.id = classArray.getJSONObject(j)
												.getString("classId");
										entity.name = classArray.getJSONObject(
												j).getString("className");
										classlList.add(entity);
									}
								}
								classAdapter.notifyDataSetChanged();
								load.dismiss();
								classDialog.show();
							} else {
								load.dismiss();
								showToast(response.getString("msg"));
							}
						} catch (JSONException e) {
							load.dismiss();
							showToast("解析出错");
						}

					}
				});
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			if (drawerLayout.isDrawerOpen(left_menu_layout)) {
				drawerLayout.closeDrawer(left_menu_layout);
			} else if ((System.currentTimeMillis() - exitTime) > 2000) {
				DialogUtils.showToast(this, "再按一次退出程序");
				exitTime = System.currentTimeMillis();

			} else {
				finish();
				System.exit(0);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		// 左
		case R.id.person_center:
			drawerLayout.openDrawer(left_menu_layout);
			break;
		// 切换账号
		case R.id.switchover:
			Intent intent = new Intent(this, SwitchAccountsActivity.class);
			startActivityForResult(intent, 10086);
			break;
		// 我的校服
		case R.id.uniform:
			if(date_null == true){
				showToast("选购校服时要先完善个人信息哦");
				return;
			}
			
			startActivity(new Intent(HomepageActivity.this,
					ShoppingActivity.class));
			break;
		// 收藏夹
		case R.id.favorites:
			drawerLayout.closeDrawers();
			startActivity(new Intent(HomepageActivity.this,
					FavoriteActivity.class));
			break;

		// 未收货
		case R.id.not_receiving:
			drawerLayout.closeDrawer(Gravity.LEFT);
			startActivity(new Intent(HomepageActivity.this,
					UnReceiveActivity.class));
			break;

		// 未收货
		case R.id.had_receiving:
			drawerLayout.closeDrawer(Gravity.LEFT);
			startActivity(new Intent(HomepageActivity.this,
					ReceivedActivity.class));
			break;

		// 全部订单
		case R.id.all_orders:
			drawerLayout.closeDrawer(Gravity.LEFT);
			startActivity(new Intent(HomepageActivity.this,
					AllOrderActivity.class));
			break;
		// 邀请
		case R.id.invitation:
			drawerLayout.closeDrawer(Gravity.LEFT);
			startActivity(new Intent(HomepageActivity.this,
					InviteFriendActivity.class));
			break;
		// 设置
		case R.id.setting:
			drawerLayout.closeDrawer(Gravity.LEFT);
			startActivity(new Intent(HomepageActivity.this,
					SettingActivity.class));
			break;
		// 消息
		case R.id.message:
			drawerLayout.closeDrawer(Gravity.LEFT);
			if (news != null) {
				Intent newsIntent = new Intent(HomepageActivity.this,
						MsgActivity.class);
				newsIntent.putExtra("news", news);
				startActivity(newsIntent);
			} else {
				showToast("没有新消息");
			}
			break;

		case R.id.info_birthday:
			dateDialog.show();
			break;

		case R.id.info_sex:
			sexDialog.show();
			break;

		case R.id.info_school:
			if (schoolList.size() == 0) {
				getAllSchool();
			} else {
				schoolDialog.show();
			}
			break;

		case R.id.info_class:
			if ("".equals(schoolId)) {
				showToast("先选学校再选班级");
				return;
			}
			if (classlList.size() == 0) {
				getClassBySchool();
			} else {
				classDialog.show();
			}
			break;

		case R.id.info_height:
			Intent heightIntent = new Intent(HomepageActivity.this,
					UpdateInfoActivity.class);
			heightIntent.putExtra("flage", 1);
			heightIntent.putExtra("userId", userId);
			heightIntent.putExtra("userIdentityNumber", userIdentityNumber);
			startActivityForResult(heightIntent, heightCode);
			break;

		case R.id.info_weight:
			Intent weightIntent = new Intent(HomepageActivity.this,
					UpdateInfoActivity.class);
			weightIntent.putExtra("flage", 2);
			weightIntent.putExtra("userId", userId);
			weightIntent.putExtra("userIdentityNumber", userIdentityNumber);
			startActivityForResult(weightIntent, weightCode);
			break;

		case R.id.exit:
			getSharedPreferences("user", Activity.MODE_PRIVATE).edit().clear().commit();
			finish();
			break;

		default:
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		// 根据上面发送过去的请求吗来区别
		switch (requestCode) {
		case heightCode:
			String value_height = data.getStringExtra("value");
			height.setText(value_height);
			break;

		case weightCode:
			String value_weight = data.getStringExtra("value");
			weight.setText(value_weight);
			break;

		case nameCode:
			String value_name = data.getStringExtra("value");
			name.setText(value_name);
			nameInside.setText(value_name);
			break;
			
		case ALBUM:
			Uri uri = data.getData();
			crop(uri);
			break;
			
		case CAMERACode:
			crop(Uri.fromFile(tempFile));
			break;
			
		case CROP:
			bitmap = data.getParcelableExtra("data");
			try {
				tempFile.delete();
			} catch (Exception e) {
				// 没有建过零时文件
			}
			saveMyBitmap(bitmap);
			updateInfo(1,-1);
			dialog.dismiss();
			break;
			
		case 10086:
			userId = getSharedPreferences("user", Activity.MODE_PRIVATE).getString(
					"userId", "");
			userIdentityNumber = getSharedPreferences("user", Activity.MODE_PRIVATE)
					.getString("userIdentityNumber", "");
			getUserInfo();
		default:
			break;
		}
	}
	
	/*
	 * 剪切图片
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", getResources().getDimension(R.dimen.image_bold));
		intent.putExtra("outputY", getResources().getDimension(R.dimen.image_bold));

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, CROP);
	}
	
	private void saveMyBitmap(Bitmap mBitmap){
		  f = new File(Environment.getExternalStorageDirectory(), (userId +TEMP));
		  try {
		   f.createNewFile();
		  } catch (IOException e) {
			  
		  }
		  FileOutputStream fOut = null;
		  try {
		   fOut = new FileOutputStream(f);
		  } catch (FileNotFoundException e) {
		   e.printStackTrace();
		  }
		  mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
		  try {
		   fOut.flush();
		  } catch (IOException e) {
		   e.printStackTrace();
		  }
		  try {
		   fOut.close();
		  } catch (IOException e) {
		   e.printStackTrace();
		  }
		 }

}
